package com.junzhiit.nengji.cms.service.impl;

import java.security.KeyPair;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bainaeco.framework.bean.Email;
import com.bainaeco.framework.util.DBKey;
import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.EncryptMD5Util;
import com.junzhiit.nengji.cms.service.AuthorizeService;
import com.junzhiit.nengji.cms.service.EmailService;
import com.junzhiit.nengji.cms.web.exception.CreateSessionErrorException;
import com.junzhiit.nengji.cms.web.exception.EmailIsExistException;
import com.junzhiit.nengji.cms.web.exception.EmailNotFoundException;
import com.junzhiit.nengji.cms.web.exception.InvalidLoginTokenException;
import com.junzhiit.nengji.cms.web.exception.InvalidSystemUserException;
import com.junzhiit.nengji.cms.web.exception.MainAccountIsExistException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeErrorException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeTimeoutException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneHasUsedException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneNotFoundException;
import com.junzhiit.nengji.cms.web.exception.RegisteredFailureException;
import com.junzhiit.nengji.cms.web.exception.RoleNotFoundException;
import com.junzhiit.nengji.cms.web.exception.SetMealNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ShopInfoNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.exception.SystemUserNotFoundException;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.OrderNumberUtils;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.cms.web.util.rsa.RSACoder;
import com.junzhiit.nengji.cms.web.util.tools.DIYTools;
import com.junzhiit.nengji.cms.web.util.tools.KeyUtil;
import com.junzhiit.nengji.cms.web.vo.LoginVO;
import com.junzhiit.nengji.cms.web.vo.PhoneCodeVO;
import com.junzhiit.nengji.cms.web.vo.RegisterBaseinfoVO;
import com.junzhiit.nengji.cms.web.vo.RegisterPersonalVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.ShopInfoEditVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.RoleDAO;
import com.junzhiit.nengji.dao.SetMealDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopInfoDAO;
import com.junzhiit.nengji.dao.SystemUserDAO;
import com.junzhiit.nengji.dao.SystemUserRoleDAO;
import com.junzhiit.nengji.dao.cache.BankCardCheckCountDAO;
import com.junzhiit.nengji.dao.cache.ShopCacheDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Role;
import com.junzhiit.nengji.model.SetMeal;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopInfo;
import com.junzhiit.nengji.model.SystemUser;
import com.junzhiit.nengji.model.SystemUserRole;
import com.junzhiit.nengji.model.enums.DefaultType;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.IsChainStatus;
import com.junzhiit.nengji.model.enums.LoginType;
import com.junzhiit.nengji.model.enums.RegistStatus;
import com.junzhiit.nengji.model.enums.ShopIsPlatform;
import com.junzhiit.nengji.model.enums.ShopStatus;
import com.junzhiit.nengji.model.enums.SystemUserStatus;
import com.junzhiit.nengji.model.enums.SystemUserType;

@Service
public class AuthorizeServiceImpl extends BaseServiceImpl implements AuthorizeService {

	@Value("${key.private}")
	private String PRIVATE_KEY_PATH;

	@Autowired
	private SystemUserDAO systemUserDAO;

	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Autowired
	private ShopDAO shopDAO;

	@Autowired
	private ShopInfoDAO shopInfoDAO;

	@Autowired
	private SetMealDAO setMealDAO;

	@Autowired
	private EmailService emailService;
	
	@Autowired
	private SystemUserRoleDAO systemUserRoleDAO;
	
	@Autowired
	private RoleDAO roleDAO;
	
	@Autowired
	private ShopCacheDAO shopCacheDAO;
	
	@Autowired
	private BankCardCheckCountDAO bankCardCheckCountDAO;
	
	@Value("${upload.mall.shop.qrcode}")
	private String shopPath;
	
	@Value("${upload.temp}")
	private String uploadPath;
	
	@Value("${upload.mall.shop.info}")
	private String shopInfoPath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;
	
	@Override
	public SystemUserSessionVO auth(LoginVO login,HttpServletResponse response) {
		// RSA decoder.
		KeyPair KeyPair = KeyUtil.keyPair(PRIVATE_KEY_PATH);
		String password = "", loginToken = "";
		try {
			loginToken = DIYTools.URLDecoder(login.getLoginToken());
			password = RSACoder.decrypt(loginToken, KeyPair.getPrivate());
		} catch (Exception e) {
			throw new InvalidLoginTokenException("Invalid login token.");
		}
		String MD5password = EncryptMD5Util.getMD5(password);
		// login
		SystemUser systemUser = systemUserDAO.login(login.getLoginName(), MD5password);
		if (systemUser == null) {
			throw new SystemUserNotFoundException("登录名或密码错误。");
		}

		if (systemUser.getStatus().intValue() == SystemUserStatus.INACTIVE.toIntStatus()) {
			throw new InvalidSystemUserException("无效的账号，请联系管理员！");
		}

		if (login.getType().intValue() != systemUser.getPlatform().intValue()) {
			throw new SystemUserNotFoundException("登录名或密码错误。");
		}
		
		SystemUserSessionVO session = new SystemUserSessionVO();
		BeanUtils.copyProperties(systemUser, session);
		Long timestamp = new Date().getTime();
		session.setSessionId(DBKey.getUUID());
		session.setSystemUserId(systemUser.getId());
		session.setLoginTime(timestamp);
		session.setLastAccessTime(timestamp);
		session.setLoginType(login.getType());
		session.setLoginMethod(login.getMethod());
		session.setLoginName(login.getLoginName());
		session.setUserName(systemUser.getName());
		session.setIsChain(systemUser.getIsChain());
		session.setIsPlatform(systemUser.getIsPlatform());
		
		if (login.getType().intValue() == LoginType.SHOP.toIntType()) {
			session.setSystemId(systemUser.getSystemId());
		}
		
		// create session.
		String key = DIYKey.getSessionHashKey(session.getSessionId());
		boolean is = systemUserCacheDAO.addHash(key, session);
		if (!is) {
			throw new CreateSessionErrorException("create session error...");
		}
		
		return session;
	}

	@Override
	public void logout(String sessionId,HttpServletRequest request,HttpServletResponse response) {
		String key = DIYKey.getSessionHashKey(sessionId);
		systemUserCacheDAO.del(key);
	}

	@Transactional
	@Override
	public SystemUserSessionVO registerBaseinfo(RegisterBaseinfoVO registerBaseinfoVO,HttpServletResponse response) {
		// RSA decoder.
		KeyPair KeyPair = KeyUtil.keyPair(PRIVATE_KEY_PATH);
		String registerToken = "", registerTokenUrl = "";
		try {
			registerTokenUrl = DIYTools.URLDecoder(registerBaseinfoVO.getRegisterToken());
			registerToken = RSACoder.decrypt(registerTokenUrl, KeyPair.getPrivate());
		} catch (Exception e) {
			throw new InvalidLoginTokenException("Invalid login token.");
		}
		Map<String, String> content = DIYTools.splitForm(registerToken);
		String mobilePhone = content.get("mobilePhone");
		String password = content.get("password");
		String code = content.get("code");
		String name = content.get("name");
		String email = content.get("email");
		PhoneCodeVO phoneCode = systemUserCacheDAO.getHash(DIYKey.getMobilePhoneCodeKey(mobilePhone),
				PhoneCodeVO.class);
		// 验证码不一致
		if (!phoneCode.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}
		int count = systemUserDAO.getMobilePhoneCount(mobilePhone);
		// 已存在手机号码
		if (count > 0) {
			throw new MobilePhoneHasUsedException("手机号码已存在,请登录！");
		}
		int countEmail = systemUserDAO.checkEmail(email);
		if (countEmail > 0) {
			throw new EmailIsExistException("邮箱已存在");
		}
		SystemUser systemUser = new SystemUser();
		String MD5password = EncryptMD5Util.getMD5(password);
		systemUser.setPassword(MD5password);
		systemUser.setMobilePhone(mobilePhone);
		systemUser.setName(name);
		systemUser.setIsMainAccount(Is.YES.toIntValue());
		systemUser.setGender(registerBaseinfoVO.getGender());
		systemUser.setEmail(email);
		systemUser.setPlatform(SystemUserType.SHOP.toIntStatus());
		systemUser.setStatus(SystemUserStatus.ACTIVE.toIntStatus());
		systemUser.setIsAuth(Is.NO.toIntValue());
		systemUser.setIsUpdatePassword(Is.NO.toIntValue());
		systemUser.setSafetyLevel(0);
		systemUser.setRegiestStatus(RegistStatus.BASE.toIntStatus());
		systemUser.setIsChain(registerBaseinfoVO.getIsChain());
		systemUser.setIsPlatform(registerBaseinfoVO.getIsPlatform());
		SystemUser user = systemUserDAO.insert(systemUser);
		
		// 注册失败
		if (user == null) {
			throw new RegisteredFailureException("注册失败");
		}
		
		//添加商户默认角色
		SystemUserRole systemUserRole=new SystemUserRole();
		systemUserRole.setSystemUserId(user.getId());
		Role role=null;
		if(registerBaseinfoVO.getIsChain()==IsChainStatus.NO.toIntStatus() && registerBaseinfoVO.getIsPlatform() == ShopIsPlatform.HEADQUARTERS.toIntStatus()){
			role=roleDAO.getDefaultRole(DefaultType.SHOP.toIntStatus());
		}else if(registerBaseinfoVO.getIsChain()==IsChainStatus.YES.toIntStatus()){
			role=roleDAO.getDefaultRole(DefaultType.CHAIN.toIntStatus());
		}else if(registerBaseinfoVO.getIsChain()==IsChainStatus.NO.toIntStatus() && registerBaseinfoVO.getIsPlatform() == ShopIsPlatform.OWN.toIntStatus()){
			role=roleDAO.getDefaultRole(DefaultType.WECHAT.toIntStatus());
		}
		if(role==null){
			throw new RoleNotFoundException("默认角色不存在");
		}
		systemUserRole.setRoleId(role.getId());
		
		
		systemUserRoleDAO.insert(systemUserRole);
		
		
		
		SystemUserSessionVO session = new SystemUserSessionVO();
		Long timestamp = new Date().getTime();
		session.setSessionId(DBKey.getUUID());
		session.setSystemUserId(user.getId());
		session.setLoginTime(timestamp);
		session.setLoginType(registerBaseinfoVO.getType());
		session.setLoginMethod(registerBaseinfoVO.getMethod());
		session.setLoginName(mobilePhone);
		session.setUserName(user.getName());

		if (registerBaseinfoVO.getType().intValue() == LoginType.SHOP.toIntType()) {
			session.setSystemId("shopId");
		}
		// create session.
		String key = DIYKey.getSessionHashKey(session.getSessionId());
		boolean is = systemUserCacheDAO.addHash(key, session);
		if (!is) {
			throw new CreateSessionErrorException("create session error...");
		}
		
		return session;
	}

	@Transactional
	public ResultVO registerShopAdd(RegisterPersonalVO registerPersonalVO, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		SystemUser systemUser = systemUserDAO.query(systemUserSessionVO.getSystemUserId());
		if (systemUser == null) {
			throw new SystemUserNotFoundException("找不到用户");
		}
		int count = shopDAO.checkMainAccount(systemUserSessionVO.getSystemUserId());
		if (count > 0) {
			throw new MainAccountIsExistException("主体账号已存在");
		}
		try {
			Shop shop = new Shop();
			Long index = shopCacheDAO.incr(DIYKey.getShopCodeStringKey());
			String code = OrderNumberUtils.getSystemCode(OrderNumberUtils.SHOP_NUMBER_PREFIX, index.intValue());
			shop.setCode(code);
			shop.setName(registerPersonalVO.getName());
			shop.setAddress(registerPersonalVO.getAddress());
			shop.setMainAccountId(systemUserSessionVO.getSystemUserId());
			shop.setType(registerPersonalVO.getType());
			shop.setStatus(ShopStatus.STOP.toIntStatus());
			shop.setLinkman(registerPersonalVO.getLinkman());
			shop.setMobilePhone(registerPersonalVO.getMobilePhone());
			shop.setIndustryId(registerPersonalVO.getIndustryId());
			shop.setAreaProvinceId(registerPersonalVO.getAreaProvinceId());
			shop.setAreaCityId(registerPersonalVO.getAreaCityId());
			shop.setAreaCountyId(registerPersonalVO.getAreaCountyId());
			shop.setProfit(registerPersonalVO.getProfit());
			shop.setIsPlatform(systemUser.getIsPlatform());
			Shop param = shopDAO.insert(shop);
			
			if (param == null) {
				throw new RegisteredFailureException("注册失败！");
			}
			// 插入shopInfo表
			 ShopInfo shopInfo = new ShopInfo();
			 shopInfo.setShopId(param.getId());
			 shopInfoDAO.insert(shopInfo);

			// 更新systemUser表
			systemUser.setSystemId(param.getId());
			systemUser.setRegiestStatus(RegistStatus.SHOP.toIntStatus());
			systemUser.setIsImproveShop(Is.YES.toIntValue());
			systemUserDAO.update(systemUser);
			result.setData(param.getId());

			// 创建session
			systemUserSessionVO.setSystemId(param.getId());
			boolean is = systemUserCacheDAO.addHash(DIYKey.getSessionHashKey(sessionId), systemUserSessionVO);
			if (!is) {
				throw new CreateSessionErrorException("create session error...");
			}
			
			// 创建该店铺验证银行卡次数
			String key = DIYKey.getBankCardCheckCount(systemUserSessionVO.getSystemId());
			bankCardCheckCountDAO.addString(key,"3");
				
		} catch (Exception e) {
			throw new RegisteredFailureException("注册失败！");
		}
		return result;
	}

	@Transactional
	@Override
	public ResultVO registerMeal(String setMealId, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		SystemUser systemUser = systemUserDAO.query(systemUserSessionVO.getSystemUserId());
		if (systemUser == null) {
			throw new SystemUserNotFoundException("找不到用户");
		}
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("找不到门店");
		}
		SetMeal setMeal = setMealDAO.query(setMealId);
		if (setMeal == null) {
			throw new SetMealNotFoundException("套餐为空！");
		}
		shop.setSetMealId(setMealId);
		shopDAO.update(shop);
		// 临时
		systemUser.setIsAuth(Is.YES.toIntValue());
		systemUser.setRegiestStatus(RegistStatus.INDUSTRY.toIntStatus());
		systemUser.setIsImproveMeal(Is.YES.toIntValue());
		systemUserDAO.update(systemUser);
		return result;
	}
	
	@Transactional
	@Override
	public ResultVO registerBusiness(ShopInfoEditVO shopInfoEditVO){
		
		ResultVO result=new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(shopInfoEditVO.getSessionId()),
				SystemUserSessionVO.class);
		SystemUser systemUser = systemUserDAO.query(systemUserSessionVO.getSystemUserId());
		if (systemUser == null) {
			throw new SystemUserNotFoundException("找不到用户");
		}
		
		ShopInfo shopInfo=shopInfoDAO.query(shopInfoEditVO.getId());
		if(shopInfo==null){
			throw new ShopInfoNotFoundException("营业执照信息是不存在的");
		}
		
		ShopInfo newShopInfo=new ShopInfo();
		BeanUtils.copyProperties(shopInfoEditVO, newShopInfo);
		shopInfoDAO.update(newShopInfo);
		
		String identityFrontImgUrl=shopInfo.getIdentityFrontImgUrl();
		String newIdentityFrontImgUrl=shopInfoEditVO.getIdentityFrontImgUrl();
		if(StringUtils.isNotBlank(newIdentityFrontImgUrl) && !newIdentityFrontImgUrl.equals(identityFrontImgUrl)){
			//FileUtil.moveFile(uploadPath + newIdentityFrontImgUrl, shopInfoPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,newIdentityFrontImgUrl, shopInfoPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+newIdentityFrontImgUrl);
			}
		}
		
		String identityBackImgUrl=shopInfo.getIdentityBackImgUrl();
		String newIdentityBackImgUrl=shopInfoEditVO.getIdentityBackImgUrl();
		if(StringUtils.isNotBlank(newIdentityBackImgUrl) && !newIdentityBackImgUrl.equals(identityBackImgUrl)){
			//FileUtil.moveFile(uploadPath + newIdentityBackImgUrl, shopInfoPath);		
			boolean is = AliyunOSSClientUtil.moveFile(backetName,newIdentityBackImgUrl, shopInfoPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+newIdentityBackImgUrl);
			}
		}
		
		
		String identityImgUrl=shopInfo.getIdentityImgUrl();
		String newIdentityImgUrl=shopInfoEditVO.getIdentityImgUrl();
		if(StringUtils.isNotBlank(newIdentityImgUrl) && !newIdentityImgUrl.equals(identityImgUrl)){
			//FileUtil.moveFile(uploadPath + newIdentityImgUrl, shopInfoPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,newIdentityImgUrl, shopInfoPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+newIdentityImgUrl);
			}
		}
		
		String subjectImgUrl=shopInfo.getSubjectImgUrl();
		String newSubjectImgUrl=shopInfoEditVO.getSubjectImgUrl();
		
		if(StringUtils.isNotBlank(newSubjectImgUrl) && !newSubjectImgUrl.equals(subjectImgUrl)){
			//FileUtil.moveFile(uploadPath + newSubjectImgUrl, shopInfoPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,newSubjectImgUrl, shopInfoPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+newSubjectImgUrl);
			}
		}
		
		Shop param=new Shop();
		param.setId(shopInfo.getShopId());
		shopDAO.update(param);
		
		systemUser.setRegiestStatus(RegistStatus.SHOPINFO.toIntStatus());
		systemUser.setIsImproveBusiness(Is.YES.toIntValue());
		systemUserDAO.update(systemUser);
		
		return result;
	}

	@Override
	public ResultVO retrievePwdPhone(String passwordToken) {
		ResultVO result = new ResultVO();
		KeyPair KeyPair = KeyUtil.keyPair(PRIVATE_KEY_PATH);
		String retrievePwdToken = "", registerTokenUrl = "";
		try {
			registerTokenUrl = DIYTools.URLDecoder(passwordToken);
			retrievePwdToken = RSACoder.decrypt(registerTokenUrl, KeyPair.getPrivate());
		} catch (Exception e) {
			throw new InvalidLoginTokenException("Invalid login token.");
		}
		Map<String, String> content = DIYTools.splitForm(retrievePwdToken);
		String mobilePhone = content.get("mobilePhone");
		String password = content.get("password");
		String code = content.get("code");
		Integer method = Integer.parseInt(content.get("method"));

		int count = systemUserDAO.getMobilePhoneCount(mobilePhone);
		if (count <= 0) {
			throw new MobilePhoneNotFoundException("找不到手机号码");
		}
		PhoneCodeVO phoneCode = systemUserCacheDAO.getHash(DIYKey.getMobilePhoneCodeKey(mobilePhone),
				PhoneCodeVO.class);
		if (!phoneCode.getCode().equals(code)) {
			// 验证码不一致
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}

		SystemUser systemUser = systemUserDAO.findByMobilePhone(mobilePhone);
		String md5Pwd = EncryptMD5Util.getMD5(password);
		systemUser.setPassword(md5Pwd);
		systemUserDAO.update(systemUser);
		return result;
	}

	@Override
	public ResultVO getPhoneCodePwd(String mobilePhone) {
		ResultVO result = new ResultVO();
		int count = systemUserDAO.getMobilePhoneCount(mobilePhone);
		if (count <= 0) {
			throw new MobilePhoneNotFoundException("找不到手机号码");
		}
		String smsModel=SmsUtil.ALIYUN_SMS_RETRIEVE_PASSWORD_CODE;
		SmsUtil.sendPhoneCode(mobilePhone, smsModel);
		return result;
	}

	@Override
	public ResultVO retrievePwdEmail(String passwordToken) {
		ResultVO result = new ResultVO();
		
		KeyPair KeyPair = KeyUtil.keyPair(PRIVATE_KEY_PATH);
		String retrievePwdToken = "", registerTokenUrl = "";
		try {
			registerTokenUrl = DIYTools.URLDecoder(passwordToken);
			retrievePwdToken = RSACoder.decrypt(registerTokenUrl, KeyPair.getPrivate());
		} catch (Exception e) {
			throw new InvalidLoginTokenException("Invalid login token.");
		}
		Map<String, String> content = DIYTools.splitForm(retrievePwdToken);
		String email = content.get("email");
		String password = content.get("password");
		String code = content.get("code");
		Integer method = Integer.parseInt(content.get("method"));

		int count = systemUserDAO.checkEmail(email);
		if (count <= 0) {
			throw new EmailNotFoundException("找不到邮箱");
		}
		PhoneCodeVO phoneCode = systemUserCacheDAO.getHash(DIYKey.getEmailCodeKey(email), PhoneCodeVO.class);
		if (!phoneCode.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}
		SystemUser systemUser = systemUserDAO.findByEmail(email);
		String md5Pwd = EncryptMD5Util.getMD5(password);
		systemUser.setPassword(md5Pwd);
		systemUserDAO.update(systemUser);
		return result;
	}

	@Override
	public ResultVO retrievePwdSetEmail(String email) {
		ResultVO result = new ResultVO();
		int count = systemUserDAO.checkEmail(email);
		if (count <= 0) {
			throw new EmailNotFoundException("找不到邮箱");
		}
		String randCode = RandomStringUtils.randomNumeric(6);// create verify
																// 随机生成6位验证码
		// 设置验证码有效时间为10分钟
		Integer timeInt = 10;// 有效时间\分钟
		Date time = DateUtil.addMins(new Date(), timeInt);

		Email mail = new Email();
		mail.setName(Constants.MALL_NAME_KEY);
		mail.setReceivers(new String[] { email });
		mail.setSubject(Constants.EMAIL_SUBJECT_FIND_PWD_KEY);
		mail.setBody(Constants.EMAIL_BODY_CODE_TEMPLATE_KEY.replace("{code}", randCode).replace("{time}",
				timeInt.toString()));
		try {
			emailService.sendEmail(mail);
			String key = DIYKey.getEmailCodeKey(email);
			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(time.getTime());
			boolean is = systemUserCacheDAO.addHash(key, code);
			if (!is) {
				throw new CreateSessionErrorException("create session error...");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
